import {baseUrl, getLoginToken, updateWXInfo} from '../api/index'
import {getUserInfo} from './getUserInfo'
import {getUserLocation} from './getLocation'

export const appLogin = (sharedOpenid) => {
  return new Promise((resolve, reject) => {
    // wx.getSetting({
    //   success (res) {
    //     if (!res.authSetting['scope.userLocation']) {
    //       wx.authorize({
    //         scope: 'scope.userLocation',
    //         success () {
    //           console.log('获取位置权限成功！')
    //         }
    //       })
    //     }
    //   }
    // })
  
    // 登录
    wx.login({
      success (res) {
        let _openid = sharedOpenid || '0'
        getLoginToken(res.code, _openid, 'isLogin').then((res) => {
          console.log('get-token', res)
          wx.setStorageSync('user_openid', res.data.info.openid)
          wx.setStorageSync('auth_token', res.data.info.token)
          Promise.all([getUserInfo(), getUserLocation()]).then(userRes => {
            console.log('userRes', userRes)
            let _userInfo = userRes[0].userInfo
            let _userLocation = userRes[1]
            wx.setStorageSync('user_location_x', _userLocation.latitude)
            wx.setStorageSync('user_location_y', _userLocation.longitude)
            updateWXInfo(_userInfo.nickName, _userInfo.avatarUrl).then(data => {
              resolve(_userInfo)
              console.log('更新用户信息成功')
            }).catch(err => {
              reject(err)
              console.log('更新用户信息失败', err.data && err.data.info)
            })
          }).catch(err => {
            reject(err)
            // setTimeout(() => {
            //   wx.openSetting({
            //     success: res => {
            //       console.log(res.authSetting)
            //     }
            //   })
            // }, 2000)
            wx.navigateTo({
              url: '/pages/index/get-wx-auth'
            })
          })
        }).catch(err => {
          wx.showToast({
            icon: 'none',
            title: err.data && err.data.info
          })
          reject(err)
        })
      },
      fail (fail) {
        wx.showModal({
          title: '提示',
          content: fail.errMsg
        })
        reject(fail)
      }
    })
  })
}
